package com.example.administrator.httpclient;

import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    protected static final  int SUCCESS=1;
    protected static final int ERROR=2;
    private HttpURLConnection httpURLConnection;
    private EditText et_path;
    private TextView tv_result;
    private Button button;
    private Handler handler =new Handler(){
        public void handleMessage(Message msg){
            switch (msg.what){//处理消息 运行在主线程
                case SUCCESS:
                    String text=(String)msg.obj;//从主线程读到的信息
                    tv_result.setText(text);//显示到textview里面
                    break;
                case ERROR:
                    //用tosat方式显示 请求失败
                    Toast.makeText(MainActivity.this, "请求失败", Toast.LENGTH_SHORT).show();
                    break;

            }

      }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.a);
        et_path=(EditText)findViewById(R.id.editText);
        tv_result=(TextView)findViewById(R.id.textView);
        button=(Button)findViewById(R.id.button);
        button.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        System.out.println("按钮被按下!");
        //获取文本输入的网址 转为STRING 去掉空格
        final String path=et_path.getText().toString().trim();
        //定义线程 访问网络吧html jsp
        new Thread(){
        public void run() {
            try {
                URL url = new URL(path);
                httpURLConnection = (HttpURLConnection) url.openConnection();
                httpURLConnection.setRequestMethod("GET");
                int code = httpURLConnection.getResponseCode();
                if (code == 200) {
                    InputStream is = httpURLConnection.getInputStream();
                    String result = StreamTools.readStream(is);
                    //通信
                    Message msg = Message.obtain();
                    msg.obj = result;
                    msg.what = SUCCESS;
                    handler.sendMessage(msg);
                }
            } catch (Exception e) {
                Message msg = Message.obtain();
                msg.what = ERROR;
                handler.sendMessage(msg);
                e.printStackTrace();
            }
        }
        }.start();
    }
}
